/**
 * Accountresumes
 *
 * for AccountresumesController
 */
var Accountresumes = {};

/**
 * functions to execute when document is ready
 *
 * only for AccountresumesController
 *
 * @return void
 */
Accountresumes.documentReady = function() {
    Accountresumes.addContact();
    Accountresumes.removeContact();
    Accountresumes.addPaymentschedule();
    Accountresumes.addPaymentscheduleManual();
    Accountresumes.removePaymentschedule();
    Accountresumes.GrossPremium();
    Accountresumes.NettPremium();
    Accountresumes.OrderPremium();
    Accountresumes.TotalDays();
    Accountresumes.Amount();
    Accountresumes.AihSplit();
    Accountresumes.addMarket();
    Accountresumes.removeMarket();
    Accountresumes.currency();
    Accountresumes.country();
    Accountresumes.parseCurrency();
    Accountresumes.UnderWriterRates();
    Accountresumes.MarketRates();
    Accountresumes.required();
    Accountresumes.sortDD('all');
}

/**
 * add meta field
 *
 * @return void
 */
Accountresumes.addContact = function() {
    $('a.addContactField').click(function() {
        var t_contact = $(this).attr('rel');
        var sb, id, text, html, rel_html;
        switch(t_contact*1) {
            case 1:
                sb = $('select#ReinsurerReinsurer option:selected');
                id = sb.val();
                text = sb.text();
                if(id != '' && text != '') {
                    html =  '<div class="contactField" style="text-align:left">';
                    html += '   <span class="size-span" style="width: 260px; float:left">';
                    html +=         text;
                    html += '       <input type="hidden" name="Reinsurers[]" value="'+id+'" />';
                    html += '   </span>';
                    html += '   <span style="float:right; font-weight:bold"><a class="removeContactField" href="JavaScript:void(0);" title="'+text+'" rel="1:::'+id+'">X</a></span>';
                    html += '</div>';
                    $('#Reinsurer').before(html);
                    $("select#ReinsurerReinsurer option[value='"+id+"']").remove();
                    rel_html =  '<div id="rel_reinsurer'+id+'" class="wrapper-pt">';
                    rel_html += '   <span class="sp-pt">'+text+' : </span>';
                    rel_html += '   <input type="text" value="" class="inp-pt size-inp1" name="ReinsurerRates[]"> % <label class="error-message">(*)</label>';  
                    rel_html += '</div>';
                    $('#Rel_Reinsurer').before(rel_html);
                }
                break;
            case 2:
                sb = $('select#ProducingbrokerProducingbroker option:selected');
                id = sb.val();
                text = sb.text();
                if(id != '' && text != '') {
                    html =  '<div class="contactField" style="text-align:left">';
                    html += '   <span class="size-span" style="width: 260px; float:left">';
                    html +=         text;
                    html += '       <input type="hidden" name="Producingbrokers[]" value="'+id+'" />';
                    html += '   </span>';
                    html += '   <span style="float:right; font-weight:bold"><a class="removeContactField" href="JavaScript:void(0);" title="'+text+'" rel="2:::'+id+'">X</a></span>';
                    html += '</div>';
                    $('#Producingbroker').before(html);
                    $("select#ProducingbrokerProducingbroker option[value='"+id+"']").remove();
                    $('select#PaymentFromId').append('<option value="'+id+'">'+text+'</option>');
                    Accountresumes.sortDD('PaymentFromId');
                }
                break;
            case 3:
                sb = $('select#OriginalinsurerOriginalinsurer option:selected');
                id = sb.val();
                text = sb.text();
                if(id != '' && text != '') {
                    html =  '<div class="contactField" style="text-align:left">';
                    html += '   <span class="size-span" style="width: 260px; float:left">';
                    html +=         text;
                    html += '       <input type="hidden" name="Originalinsurers[]" value="'+id+'" />';
                    html += '   </span>';
                    html += '   <span style="float:right; font-weight:bold"><a class="removeContactField" href="JavaScript:void(0);" title="'+text+'" rel="3:::'+id+'">X</a></span>';
                    html += '</div>';
                    $('#Originalinsurer').before(html);
                    $("select#OriginalinsurerOriginalinsurer option[value='"+id+"']").remove();
                    rel_html =  '<table id="rel_originalinsurer'+id+'" cellspacing="0" cellpadding="0" border="0">';
                    rel_html += '   <tr>';
                    rel_html += '       <td style="padding-left:50px">';
                    rel_html += '           <span class="sp-pt">'+text+' : </span>';
                    rel_html += '           <input type="text" value="" class="inp-pt size-inp1" name="OriginalinsurerRates[]"> % <label class="error-message">(*)</label>';
                    rel_html += '       </td>';
                    rel_html += '   </tr>';
                    rel_html += '</table>';
                    $('#Rel_Originalinsurer').before(rel_html);
                }
                break;
            case 4:
                sb = $('select#MarketMarket option:selected');
                id = sb.val();
                text = sb.text();
                if(id != '' && text != '') {
                    html =  '<div class="contactField" style="text-align:left">';
                    html += '   <span class="size-span" style="width: 260px; float:left">';
                    html +=         text;
                    html += '       <input type="hidden" name="Markets[]" value="'+id+'" />';
                    html += '   </span>';
                    html += '   <span style="float:right; font-weight:bold"><a class="removeContactField" href="JavaScript:void(0);" title="'+text+'" rel="4:::'+id+'">X</a></span>';
                    html += '</div>';
                    $('#Market').before(html);
                    $("select#MarketMarket option[value='"+id+"']").remove();
                }
                break;
            default:
                break;
        }
        $('a.removeContactField').unbind();
        Accountresumes.removeContact();
        return false;
    });
}
Accountresumes.addMarket = function() {
    $('a.addMarketField').click(function() {
        var checkfrm = $('a.checkfrm').attr('rel');
        if(checkfrm=='add') {
            $('a.checkfrm').attr('rel', 'second')
            $('.payment-schedule-all').remove();
            
            var sb, id, text, html, rel_html, rel_html2;
            sb = $('select#MarketMarket option:selected');
            id = sb.val();
            text = sb.text();
            if(id != '' && text != '') {
                html =  '<div id="marketField'+id+'" class="marketField" style="text-align:left">';
                html += '   <span class="size-span" style="width: 260px; float:left">';
                html +=         text;
                html += '       <input type="hidden" name="Markets[]" value="'+id+'" />';
                html += '   </span>';
                html += '   <span style="float:right; font-weight:bold"><a class="removeMarketField" href="JavaScript:void(0);" title="'+text+'" rel="4:::'+id+'">X</a></span>';
                html += '</div>';
                $('#Market').before(html);

                $("select#MarketMarket option[value='"+id+"']").remove();
                $.get(Croogo.basePath+'admin/accountresumes/add_placementdetail/'+id, function(data) {
                    $('#placementdetailField').before(data);
                    Accountresumes.removeMarket();
                    Accountresumes.required();
                    Accountresumes.AihSplit();
                });
            }
            $('a.removeMarketField').unbind();
            $('a.removeMarketField2').unbind();
            Accountresumes.UnderWriterRates();
            Accountresumes.MarketRates();
        } else {
            if(confirm("If you add this, you must setup 'placement details' and 'payment schedule' again. Do you want to continue?")) {
                var payment_schedule_id = '';
                $.each($('span.delete_payment_schedule'), function(){ 
                    payment_schedule_id += payment_schedule_id==''? $(this).attr('rel') : '-'+$(this).attr('rel');
                });
                if(payment_schedule_id!='') {
                    $.getJSON(Croogo.basePath+'admin/accountresumes/delete_paymentschedule/'+payment_schedule_id, function(data) {
                        if (data.success) {
                            $('.payment-schedule-all').remove();
                        } else {
                            // error
                        }
                    });
                } else {
                    $('.payment-schedule-all').remove();
                }

                var sb, id, text, html, rel_html, rel_html2;
                sb = $('select#MarketMarket option:selected');
                id = sb.val();
                text = sb.text();
                if(id != '' && text != '') {
                    html =  '<div id="marketField'+id+'" class="marketField" style="text-align:left">';
                    html += '   <span class="size-span" style="width: 260px; float:left">';
                    html +=         text;
                    html += '       <input type="hidden" name="Markets[]" value="'+id+'" />';
                    html += '   </span>';
                    html += '   <span style="float:right; font-weight:bold"><a class="removeMarketField" href="JavaScript:void(0);" title="'+text+'" rel="4:::'+id+'">X</a></span>';
                    html += '</div>';
                    $('#Market').before(html);

                    $("select#MarketMarket option[value='"+id+"']").remove();
                    $.get(Croogo.basePath+'admin/accountresumes/add_placementdetail/'+id, function(data) {
                        $('#placementdetailField').before(data);
                        Accountresumes.removeMarket();
                        Accountresumes.required();
                        Accountresumes.AihSplit();
                    });
                }
                $('a.removeMarketField').unbind();
                $('a.removeMarketField2').unbind();
                Accountresumes.UnderWriterRates();
                Accountresumes.MarketRates();
            }
        }
        return false;
    });
}

Accountresumes.getUnderWriterName = function(id) {
    if(id) {
        $.getJSON(Croogo.basePath+'admin/accountresumes/get_underwriter/'+id, function(data) {
            if (data.success) {
                $('#underwriter_id'+id).html(data.underwriter + ' : ');
            } else {
                // error
            }
        });
    }
}

/**
 * remove meta field
 *
 * @return void
 */
Accountresumes.removeContact = function() {
    $('a.removeContactField').click(function() {
        var checkfrm = $('a.checkfrm').attr('rel');
        if(checkfrm=='add') {
            $('a.checkfrm').attr('rel', 'second');
            var that = $(this);
            var temp = that.attr('rel').split(':::');
            var text = that.attr('title');
            switch(temp[0]*1) {
                case 1:
                    $("select#ReinsurerReinsurer").append('<option value="'+temp[1]+'">'+text+'</option>');
                    $('#rel_reinsurer'+temp[1]).remove();
                    break;
                case 2:
                    $("select#ProducingbrokerProducingbroker").append('<option value="'+temp[1]+'">'+text+'</option>');
                    Accountresumes.sortDD('ProducingbrokerProducingbroker');
                    $("select#PaymentFromId option[value='"+temp[1]+"']").remove();

                    // delete payment schedule
                    $('.payment-schedule-all').remove();
                    break;
                case 3:
                    $("select#OriginalinsurerOriginalinsurer").append('<option value="'+temp[1]+'">'+text+'</option>');
                    $('#rel_originalinsurer'+temp[1]).remove();
                    break;
                case 4:
                    $("select#MarketMarket").append('<option value="'+temp[1]+'">'+text+'</option>');
                    break;
                default:
                    break;
            }
            that.parents('.contactField').remove();
        } else {
            if($('div.contactField').length>1) {
                if(confirm("If you delete this, you must setup 'placement details' and 'payment schedule' again. Do you want to continue?")) {
                    var that = $(this);
                    var temp = that.attr('rel').split(':::');
                    var text = that.attr('title');
                    switch(temp[0]*1) {
                        case 1:
                            $("select#ReinsurerReinsurer").append('<option value="'+temp[1]+'">'+text+'</option>');
                            $('#rel_reinsurer'+temp[1]).remove();
                            break;
                        case 2:
                            $("select#ProducingbrokerProducingbroker").append('<option value="'+temp[1]+'">'+text+'</option>');
                            Accountresumes.sortDD('ProducingbrokerProducingbroker');
                            $("select#PaymentFromId option[value='"+temp[1]+"']").remove();

                            // delete payment schedule
                            var payment_schedule_id = '';
                            $.each($('span.delete_payment_schedule'), function(){ // 'span.payer'+temp[1]
                                payment_schedule_id += payment_schedule_id==''? $(this).attr('rel') : '-'+$(this).attr('rel');
                            });
                            if(payment_schedule_id!='') {
                                $.getJSON(Croogo.basePath+'admin/accountresumes/delete_paymentschedule/'+payment_schedule_id, function(data) {
                                    if (data.success) {
                                        $('.payment-schedule-all').remove();
                                    } else {
                                        // error
                                    }
                                });
                            } else {
                                $('.payment-schedule-all').remove();
                            }
                            break;
                        case 3:
                            $("select#OriginalinsurerOriginalinsurer").append('<option value="'+temp[1]+'">'+text+'</option>');
                            $('#rel_originalinsurer'+temp[1]).remove();
                            break;
                        case 4:
                            $("select#MarketMarket").append('<option value="'+temp[1]+'">'+text+'</option>');
                            break;
                        default:
                            break;
                    }
                    that.parents('.contactField').remove();
                }
            } else {
                alert('You can\'t clear all Producer');
            }
        }
        return false;
    });
}

Accountresumes.removeMarket = function() {
    $('a.removeMarketField').click(function() {
        var checkfrm = $('a.checkfrm').attr('rel');
        if(checkfrm=='add') {
            $('a.checkfrm').attr('rel', 'second');
            var that = $(this);
            var temp = that.attr('rel').split(':::');
            var text = that.attr('title');

            $("select#MarketMarket").append('<option value="'+temp[1]+'">'+text+'</option>');
            Accountresumes.sortDD('MarketMarket');
            // delete placement detail
            $('#rel_market'+temp[1]).remove();
            // delete payment schedule
            $('.payment-schedule-all').remove();
            $('#marketField'+temp[1]).remove();
        } else {
            if(confirm("If you delete this, you must setup 'placement details' and 'payment schedule' again. Do you want to continue?")) {
                var that = $(this);
                var temp = that.attr('rel').split(':::');
                var text = that.attr('title');

                $("select#MarketMarket").append('<option value="'+temp[1]+'">'+text+'</option>');
                Accountresumes.sortDD('MarketMarket');
                // delete placement detail
                var cur_placementdetail_id = $('#rel_market'+temp[1]).attr('rel');
                if(cur_placementdetail_id){
                    $.getJSON(Croogo.basePath+'admin/accountresumes/delete_placementdetail/'+cur_placementdetail_id, function(data) {
                        if (data.success) {
                            $('#rel_market'+temp[1]).remove();
                        } else {
                            // error
                        }
                    });
                } else {
                    $('#rel_market'+temp[1]).remove();
                }
                // delete payment schedule
                var payment_schedule_ids = '';
                $.each($('span.delete_payment_schedule'), function(){ 
                    payment_schedule_ids += payment_schedule_ids==''? $(this).attr('rel') : '-'+$(this).attr('rel');
                });
                if(payment_schedule_ids!='') {
                    $.getJSON(Croogo.basePath+'admin/accountresumes/delete_paymentschedule/'+payment_schedule_ids, function(data) {
                        if (data.success) {
                            $('.payment-schedule-all').remove();
                        } else {
                            // error
                        }
                    });
                } else {
                    $('.payment-schedule-all').remove();
                }
                $('#marketField'+temp[1]).remove();
            }
        }
        return false;
    });
    
    $('a.removeMarketField2').click(function() {
        var checkfrm = $('a.checkfrm').attr('rel');
        if(checkfrm=='add') {
            $('a.checkfrm').attr('rel', 'second');
            var that = $(this);
            var temp = that.attr('rel').split(':::');
            var text = that.attr('title');

            $("select#MarketMarket").append('<option value="'+temp[1]+'">'+text+'</option>');
            Accountresumes.sortDD('MarketMarket');
            // delete placement detail
            $('#rel_market'+temp[1]).remove();
            // delete payment schedule
            $('.payment-schedule-all').remove();
            $('#marketField'+temp[1]).remove();
        } else {
            if(confirm("If you delete this, you must setup 'placement details' and 'payment schedule' again. Do you want to continue?")) {
                var that = $(this);
                var temp = that.attr('rel').split(':::');
                var text = that.attr('title');

                $("select#MarketMarket").append('<option value="'+temp[1]+'">'+text+'</option>');
                Accountresumes.sortDD('MarketMarket');
                // delete placement detail
                var cur_placementdetail_id = $('#rel_market'+temp[1]).attr('rel');
                if(cur_placementdetail_id){
                    $.getJSON(Croogo.basePath+'admin/accountresumes/delete_placementdetail/'+cur_placementdetail_id, function(data) {
                        if (data.success) {
                            $('#rel_market'+temp[1]).remove();
                        } else {
                            // error
                        }
                    });
                } else {
                    $('#rel_market'+temp[1]).remove();
                }
                // delete payment schedule
                var payment_schedule_ids = '';
                $.each($('span.delete_payment_schedule'), function(){ 
                    payment_schedule_ids += payment_schedule_ids==''? $(this).attr('rel') : '-'+$(this).attr('rel');
                });
                if(payment_schedule_ids!='') {
                    $.getJSON(Croogo.basePath+'admin/accountresumes/delete_paymentschedule/'+payment_schedule_ids, function(data) {
                        if (data.success) {
                            $('.payment-schedule-all').remove();
                        } else {
                            // error
                        }
                    });
                } else {
                    $('.payment-schedule-all').remove();
                }
                $('#marketField'+temp[1]).remove();
            }
        }
        return false;
    });
}

/**
 * add meta field
 *
 * @return void
 */
Accountresumes.addPaymentschedule = function() {
    $('a.addPaymentscheduleField').click(function() {
        var payer = $('select#PaymentFromId option:selected').val();
        var payer_name = $('select#PaymentFromId option:selected').text();
        var marketers = '';
        $('input[name="Markets[]"]').each(function(){
            marketers += (marketers=='')?$(this).val():'-'+$(this).val();
        });
        $.get(Croogo.basePath+'admin/accountresumes/add_paymentschedule/'+payer+'/'+payer_name+'/'+marketers, function(data) {
            $('#paymentscheduleField').before(data);
            $('a.removePaymentscheduleField').unbind();
            Accountresumes.removePaymentschedule();
            Accountresumes.jdate();
            Accountresumes.Amount();
            Accountresumes.required();
            Accountresumes.recurrency();
        });
        return false;
    });
}

Accountresumes.addPaymentscheduleManual = function() {
    $('a.addPaymentscheduleManualField').click(function() {
        var payer = $('select#PaymentFromId option:selected').val();
        var payer_name = $('select#PaymentFromId option:selected').text();
        var marketers = '';
        $('input[name="Markets[]"]').each(function(){
            marketers += (marketers=='')?$(this).val():'-'+$(this).val();
        });
        $.get(Croogo.basePath+'admin/accountresumes/add_paymentschedulemanual/'+payer+'/'+payer_name+'/'+marketers, function(data) {
            $('#paymentscheduleField').before(data);
            $('a.removePaymentscheduleField').unbind();
            Accountresumes.removePaymentschedule();
            Accountresumes.jdate();
            Accountresumes.Amount();
            Accountresumes.required();
            Accountresumes.recurrency();
        });
        return false;
    });
}

/**
 * remove meta field
 *
 * @return void
 */
Accountresumes.removePaymentschedule = function() {
    $('a.removePaymentscheduleField').click(function() {
        var that = $(this);
        if (that.attr('rel') != '') {
            $.getJSON(Croogo.basePath+'admin/accountresumes/delete_paymentschedule/'+that.attr('rel'), function(data) {
                if (data.success) {
                    that.parents().parents().parent().parents('.payment-schedule-all').remove();
                } else {
                    // error
                }
            });
        } else {
            that.parents().parents().parent().parents('.payment-schedule-all').remove();
        }
        return false;
    });
}

Accountresumes.jdate = function() {
    $('input.jdate').datepicker({dateFormat: 'm/d/yy'});
    return false;
}

Accountresumes.GrossPremium = function(){
    $('#AccountresumeRate').not('[title="manual"]').blur(function(){
        // form validate
        if($('#AccountresumeRate').val()==''){
            $('#AccountresumeRate').parent().children('label.error-message').remove();
            $('#AccountresumeRate').after('<label class=\"error-message\">This field is required</label>');
        } else if($('#AccountresumeRate').val()*1 <= 0) {
            $('#AccountresumeRate').parent().children('label.error-message').remove();
            $('#AccountresumeRate').after('<label class=\"error-message\">This value can\'t be less than 0</label>');
        } else if($('#AccountresumeRate').val()*1 > 100) {
            $('#AccountresumeRate').parent().children('label.error-message').remove();
            $('#AccountresumeRate').after('<label class=\"error-message\">This value can\'t be greater than 100</label>');
        } else {
            var pattern = /^[1-9]{1}[0-9]*(\.[0-9]+)?$/.test($('#AccountresumeRate').val());
            var pattern2 = /^[0]{1}(\.[0-9]+)?$/.test($('#AccountresumeRate').val());
            if(pattern || pattern2){
                $('#AccountresumeRate').parent().children('label.error-message').remove();
            } else {
                $('#AccountresumeRate').parent().children('label.error-message').remove();
                $('#AccountresumeRate').after('<label class=\"error-message\">This field is invalid.</label>');
            }
        }

        var gross_premium = $('#AccountresumeSumInsured').val() * $('#AccountresumeRate').val() /100;
        
        var total_days = $('#AccountresumeTotalDays').val()*1;
        if(total_days<365) {
            gross_premium = $('#AccountresumeSumInsured').val() * $('#AccountresumeRate').val() /100 * total_days /365;
        } 
        
        if(gross_premium > 0) {
            gross_premium = Accountresumes.roundNumber(gross_premium, 2); 
            $('#AccountresumeGrossPremium').val(gross_premium);
            $('#AccountresumeGrossPremium').formatCurrency('#Gross_Premium');
            var sb = $('select#CurrencyCurrency option:selected');
            $('#AccountresumeGrossPremium').parent().parent().children('span.selected_currency').html(sb.text());
        }
        Accountresumes.recalculator();
        return false;
    });
    // manual
    $('#AccountresumeRate[title="manual"]').blur(function(){
        // form validate
        if($('#AccountresumeRate').val()==''){
            $('#AccountresumeRate').parent().children('label.error-message').remove();
            $('#AccountresumeRate').after('<label class=\"error-message\">This field is required</label>');
        } else if($('#AccountresumeRate').val()*1 <= 0) {
            $('#AccountresumeRate').parent().children('label.error-message').remove();
            $('#AccountresumeRate').after('<label class=\"error-message\">This value can\'t be less than 0</label>');
        } else if($('#AccountresumeRate').val()*1 > 100) {
            $('#AccountresumeRate').parent().children('label.error-message').remove();
            $('#AccountresumeRate').after('<label class=\"error-message\">This value can\'t be greater than 100</label>');
        } else {
            var pattern = /^[1-9]{1}[0-9]*(\.[0-9]+)?$/.test($('#AccountresumeRate').val());
            var pattern2 = /^[0]{1}(\.[0-9]+)?$/.test($('#AccountresumeRate').val());
            if(pattern || pattern2){
                $('#AccountresumeRate').parent().children('label.error-message').remove();
            } else {
                $('#AccountresumeRate').parent().children('label.error-message').remove();
                $('#AccountresumeRate').after('<label class=\"error-message\">This field is invalid.</label>');
            }
        }

        return false;
    });
//    $('#GrossPremium[title="manual"]').blur(function(){
//        // form validate
//        if($('#AccountresumeRate').val()==''){
//            $('#AccountresumeRate').parent().children('label.error-message').remove();
//            $('#AccountresumeRate').after('<label class=\"error-message\">This field is required</label>');
//        } else if($('#AccountresumeRate').val()*1 <= 0) {
//            $('#AccountresumeRate').parent().children('label.error-message').remove();
//            $('#AccountresumeRate').after('<label class=\"error-message\">This value can\'t be less than 0</label>');
//        } else if($('#AccountresumeRate').val()*1 > 100) {
//            $('#AccountresumeRate').parent().children('label.error-message').remove();
//            $('#AccountresumeRate').after('<label class=\"error-message\">This value can\'t be greater than 100</label>');
//        } else {
//            var pattern = /^[1-9]{1}[0-9]*(\.[0-9]+)?$/.test($('#AccountresumeRate').val());
//            var pattern2 = /^[0]{1}(\.[0-9]+)?$/.test($('#AccountresumeRate').val());
//            if(pattern || pattern2){
//                $('#AccountresumeRate').parent().children('label.error-message').remove();
//            } else {
//                $('#AccountresumeRate').parent().children('label.error-message').remove();
//                $('#AccountresumeRate').after('<label class=\"error-message\">This field is invalid.</label>');
//            }
//        }
//
//        return false;
//    });
    
}

Accountresumes.NettPremium = function(){
    $('#AccountresumeOrderHereon').not('[title="manual"]').blur(function(){
        // form validate
        if($('#AccountresumeOrderHereon').val()==''){
            $('#AccountresumeOrderHereon').parent().children('label.error-message').remove();
            $('#AccountresumeOrderHereon').after('<label class=\"error-message\">This field is required</label>');
        } else if($('#AccountresumeOrderHereon').val()*1 <= 0) {
            $('#AccountresumeOrderHereon').parent().children('label.error-message').remove();
            $('#AccountresumeOrderHereon').after('<label class=\"error-message\">This value can\'t be less than 0</label>');
            error = false;
        } else if($('#AccountresumeOrderHereon').val()*1 > 100) {
            $('#AccountresumeOrderHereon').parent().children('label.error-message').remove();
            $('#AccountresumeOrderHereon').after('<label class=\"error-message\">This value can\'t be greater than 100</label>');
            error = false;
        } else {
            var pattern = /^[1-9]{1}[0-9]*(\.[0-9]+)?$/.test($('#AccountresumeOrderHereon').val());
            var pattern2 = /^[0]{1}(\.[0-9]+)?$/.test($('#AccountresumeOrderHereon').val());
            if(pattern || pattern2){
                $('#AccountresumeOrderHereon').parent().children('label.error-message').remove();
            } else {
                $('#AccountresumeOrderHereon').parent().children('label.error-message').remove();
                $('#AccountresumeOrderHereon').after('<label class=\"error-message\">This field is invalid</label>');
            }
        }
        
        var nett_premium = ($('#AccountresumeSumInsured').val() * $('#AccountresumeRate').val() /100) * $('#AccountresumeOrderHereon').val() /100;
        if(nett_premium > 0) {
            nett_premium = Accountresumes.roundNumber(nett_premium, 2);
            $('#AccountresumeNettPremium').val(nett_premium);
            $('#AccountresumeNettPremium').formatCurrency('#Nett_Premium');
            var sb = $('select#CurrencyCurrency option:selected');
            $('#AccountresumeNettPremium').parent().parent().children('span.selected_currency').html(sb.text());
        }
        Accountresumes.recalculator();
        return false;
    });
    // manual
    $('#AccountresumeOrderHereon[title="manual"]').blur(function(){
        // form validate
        if($('#AccountresumeOrderHereon').val()==''){
            $('#AccountresumeOrderHereon').parent().children('label.error-message').remove();
            $('#AccountresumeOrderHereon').after('<label class=\"error-message\">This field is required</label>');
        } else if($('#AccountresumeOrderHereon').val()*1 <= 0) {
            $('#AccountresumeOrderHereon').parent().children('label.error-message').remove();
            $('#AccountresumeOrderHereon').after('<label class=\"error-message\">This value can\'t be less than 0</label>');
            error = false;
        } else if($('#AccountresumeOrderHereon').val()*1 > 100) {
            $('#AccountresumeOrderHereon').parent().children('label.error-message').remove();
            $('#AccountresumeOrderHereon').after('<label class=\"error-message\">This value can\'t be greater than 100</label>');
            error = false;
        } else {
            var pattern = /^[1-9]{1}[0-9]*(\.[0-9]+)?$/.test($('#AccountresumeOrderHereon').val());
            var pattern2 = /^[0]{1}(\.[0-9]+)?$/.test($('#AccountresumeOrderHereon').val());
            if(pattern || pattern2){
                $('#AccountresumeOrderHereon').parent().children('label.error-message').remove();
            } else {
                $('#AccountresumeOrderHereon').parent().children('label.error-message').remove();
                $('#AccountresumeOrderHereon').after('<label class=\"error-message\">This field is invalid</label>');
            }
        }
        
        return false;
    });
}

Accountresumes.OrderPremium = function(){
    $('#AccountresumeClientDiscount').not('[title="manual"]').blur(function(){
        // form validate
        if($('#AccountresumeClientDiscount').val()==''){
            $('#AccountresumeClientDiscount').parent().children('label.error-message').remove();
            $('#AccountresumeClientDiscount').after('<label class=\"error-message\">This field is required</label>');
        } else if($('#AccountresumeClientDiscount').val()*1 < 0) {
            $('#AccountresumeClientDiscount').parent().children('label.error-message').remove();
            $('#AccountresumeClientDiscount').after('<label class=\"error-message\">This value can\'t be less than 0</label>');
        } else if($('#AccountresumeClientDiscount').val()*1 == 0) {
            $('#AccountresumeClientDiscount').parent().children('label.error-message').remove();
            $('#AccountresumeClientDiscount').val(0);
        } else {
            var pattern = /^[1-9]{1}[0-9]{0,1}(\.[0-9]+)?$/.test($('#AccountresumeClientDiscount').val());
            var pattern2 = /^[0]{1}(\.[0-9]+)?$/.test($('#AccountresumeClientDiscount').val());
            if(pattern || pattern2){
                $('#AccountresumeClientDiscount').parent().children('label.error-message').remove();
            } else {
                $('#AccountresumeClientDiscount').parent().children('label.error-message').remove();
                $('#AccountresumeClientDiscount').after('<label class=\"error-message\">This field is invalid</label>');
            }
        }
        
        var order_premium = ($('#AccountresumeNettPremium').val() * (100 - $('#AccountresumeClientDiscount').val()) /100);
        if(order_premium > 0) {
            order_premium = Accountresumes.roundNumber(order_premium, 2);
            $('#AccountresumeOrderPremium').val(order_premium);
            $('#AccountresumeOrderPremium').formatCurrency('#Order_Premium');
            var sb = $('select#CurrencyCurrency option:selected');
            $('#AccountresumeOrderPremium').parent().parent().children('span.selected_currency').html(sb.text());
        }
        Accountresumes.recalculator();
        return false;
    });
    // manual
    $('#AccountresumeClientDiscount[title="manual"]').blur(function(){
        // form validate
        if($('#AccountresumeClientDiscount').val()==''){
            $('#AccountresumeClientDiscount').parent().children('label.error-message').remove();
            $('#AccountresumeClientDiscount').after('<label class=\"error-message\">This field is required</label>');
        } else if($('#AccountresumeClientDiscount').val()*1 < 0) {
            $('#AccountresumeClientDiscount').parent().children('label.error-message').remove();
            $('#AccountresumeClientDiscount').after('<label class=\"error-message\">This value can\'t be less than 0</label>');
        } else if($('#AccountresumeClientDiscount').val()*1 == 0) {
            $('#AccountresumeClientDiscount').parent().children('label.error-message').remove();
            $('#AccountresumeClientDiscount').val(0);
        } else {
            var pattern = /^[1-9]{1}[0-9]{0,1}(\.[0-9]+)?$/.test($('#AccountresumeClientDiscount').val());
            var pattern2 = /^[0]{1}(\.[0-9]+)?$/.test($('#AccountresumeClientDiscount').val());
            if(pattern || pattern2){
                $('#AccountresumeClientDiscount').parent().children('label.error-message').remove();
            } else {
                $('#AccountresumeClientDiscount').parent().children('label.error-message').remove();
                $('#AccountresumeClientDiscount').after('<label class=\"error-message\">This field is invalid</label>');
            }
        }
        
        return false;
    });
}

Accountresumes.TotalDays = function(){
    $('#AccountresumeToDate').change(function(){
        // form validate
        if($('#AccountresumeToDate').val()==''){
            $('#AccountresumeToDate').parent().children('label.error-message-second').remove();
            $('#AccountresumeToDate').after('<label class=\"error-message-second\">This field is required</label>');
        } else {
            $('#AccountresumeToDate').parent().children('label.error-message-second').remove();
        }
        
        var from = Accountresumes.parseDate('1/1/1970');
        var to = Accountresumes.parseDate('1/1/1970');
        if($('#AccountresumeFromDate').val()!='') {
            from = Accountresumes.parseDate($('#AccountresumeFromDate').val());
        } 
        if($('#AccountresumeToDate').val()!=''){
            to = Accountresumes.parseDate($('#AccountresumeToDate').val());
        } 
        var total = Accountresumes.dayDiff(from, to);
        if(total > 0) {
            $('#total_days').parent().children('label.error-message').remove();
            $('#total_days').html(total);
            $('#AccountresumeTotalDays').val(total);
            Accountresumes.recalculator();
        } else {
            $('#total_days').parent().children('label.error-message').remove();
            $('#total_days').after('<label class=\"error-message\">Total days must greater than 0</label>');
        }
        return false;
    });
    $('#AccountresumeFromDate').change(function(){
        // form validate
        if($('#AccountresumeFromDate').val()==''){
            $('#AccountresumeFromDate').parent().children('label.error-message-first').remove();
            $('#AccountresumeFromDate').after('<label class=\"error-message-first\">This field is required</label>');
        } else {
            $('#AccountresumeFromDate').parent().children('label.error-message-first').remove();
        }
        
        var from, to;
        if($('#AccountresumeToDate').val()!=''){
            from = Accountresumes.parseDate($('#AccountresumeFromDate').val());
            to = Accountresumes.parseDate($('#AccountresumeToDate').val());
            var total = Accountresumes.dayDiff(from, to);
            if(total > 0) {
                $('#total_days').parent().children('label.error-message').remove();
                $('#total_days').html(total);
                $('#AccountresumeTotalDays').val(total);
                Accountresumes.recalculator();
            } else {
                $('#total_days').parent().children('label.error-message').remove();
                $('#total_days').after('<label class=\"error-message\">Total days must greater than 0</label>');
            }
        }
        
        return false;
    })
}

Accountresumes.AihSplit = function(){
    $('a.aih_split').click(function(){
        var id = $(this).attr('id');
        var brokerage_rate = $('#Placementdetailt'+id+'BrokerageRate').val()*1;
        var aih_rate = $('#Placementdetailt'+id+'AihRate').val()*1;

        var contact_rate2 = brokerage_rate-aih_rate;
        if(contact_rate2>=0) {
            $('#Placementdetailt'+id+'AihRate').parents().children('label.error-message').remove();
            $('#Placementdetailt'+id+'ContactRate2').val(contact_rate2);
            Accountresumes.recalculator();
        } else {
            $('#Placementdetailt'+id+'AihRate').parents().children('label.error-message').remove();
            $('#Placementdetailt'+id+'AihRate').after('<label class=\"error-message\">AIH can\'t be greater than Brokerage</label>');
        }
        return false;
    });
}

Accountresumes.AihSplit2 = function(id){
    var direct_placement = $('#'+id).attr('title');
    var brokerage_rate = $('#Placementdetailt'+id+'BrokerageRate').val()*1;
    var aih_rate = $('#Placementdetailt'+id+'AihRate').val()*1;

    var contact_rate2 = brokerage_rate-aih_rate;
    if(direct_placement == 'direct_placement1') {
        aih_rate = brokerage_rate;
        $('#Placementdetailt'+id+'AihRate').val(aih_rate);
        contact_rate2 = 0;
    }
    if(contact_rate2>=0) {
        $('#Placementdetailt'+id+'AihRate').parents().children('label.error-message').remove();
        $('#Placementdetailt'+id+'ContactRate2').val(contact_rate2);
        Accountresumes.recalculator();
    } else {
        $('#Placementdetailt'+id+'AihRate').parents().children('label.error-message').remove();
        $('#Placementdetailt'+id+'AihRate').after('<label class=\"error-message\">AIH can\'t be greater than Brokerage</label>');
    }
    return false;
}

Accountresumes.Amount = function(){
    // A = (PA1 /X) * (100 - PA4) /100 * Y
    $('input.payment_schedule_amount').blur(function(){
        var id = $(this).attr('id').replace('broker_amount', '');
        $('#broker_amount'+id).formatCurrency();
        var broker_amount = $('#broker_amount'+id).val().replace(/,/gi, '')*1; // [Y]
        broker_amount = Accountresumes.roundNumber(broker_amount, 2);
        $('#Paymentschedule'+id+'BrokerAmount').val(broker_amount);
        var order_hereon = $('#AccountresumeOrderHereon').val()*1; // [X]
        var p_one, p_four, a_amount; 
        var aih_amount = 0;
        $('input[name="Markets[]"]').each(function(){
            var market_id = $(this).val();
            p_one = $('#rel_market'+market_id+' input[name*="contact_rate"]').val()*1; // PA1
            p_four = $('#rel_market'+market_id+' input[name*="aih_rate"]').val()*1; // PA4
            a_amount = (p_one /order_hereon) * (100 - p_four) /100 * broker_amount;
            a_amount = Accountresumes.roundNumber(a_amount, 2);
            aih_amount += a_amount;
            $('#Paymentschedule'+id+'RelMarketAmount'+market_id).val(a_amount);
            $('#Paymentschedule'+id+'RelMarketAmount'+market_id).formatCurrency('#market_amount'+id+market_id);
        });
        
        $('#Paymentschedule'+id+'AihAmount').val(Accountresumes.roundNumber(broker_amount - aih_amount, 2));
        $('#Paymentschedule'+id+'AihAmount').formatCurrency('#aih_amount'+id);
        
        Accountresumes.recalculator();
        return false;
    });
    
//    $('input.payment_schedule_amount_manual').each(function(){
//        var that = $(this);
//        $(this).blur(function(){
        $('input.payment_schedule_amount_manual').blur(function(){
            if($(this).val().trim() == '') {
                $(this).parent().children('label.error-message').remove();
                $(this).after('<label class=\"error-message\">This field is required</label>');
            } else {
                $(this).formatCurrency();
                var amount = $(this).val().replace(/,/gi, '')*1;
                amount = Accountresumes.roundNumber(amount, 2);
//                $(this).next().val(amount);
                $(this).parent().children('input[type=hidden]').val(amount);
                if(amount > 0) {
                    $(this).parent().children('label.error-message').remove();
                } else {
                    $(this).parent().children('label.error-message').remove();
                    $(this).after('<label class=\"error-message\">This field is invalid.</label>');
                }
            }
        });
//        });
//    });
}

Accountresumes.roundNumber = function(num, dec) {
	var result = Math.round(num*Math.pow(10, dec))/Math.pow(10, dec);
	return result;
}
Accountresumes.parseDate = function(str) {
    // mm/dd/yyyy
//    var jdate = str.split('/');
//    return new Date(jdate[2]*1, jdate[0]*1, jdate[1]*1-1);
    return new Date(str);
}

Accountresumes.dayDiff = function(first, second) {
    var to = second.getTime();
    var from = first.getTime();
    return (to-from)/(1000*60*60*24);
}

Accountresumes.currency = function() {
    $('select#CurrencyCurrency').change(function(){
        var sb = $('select#CurrencyCurrency option:selected');
        $('span.selected_currency').html(sb.text());
        $('input#AccountresumeCurrency').val(sb.text());
    });
    return false;
}

Accountresumes.country = function() {
    $('select#CountryCountry').change(function(){
        var sb = $('select#CountryCountry option:selected');
        $('input#AccountresumeCountry').val(sb.text());
    });
    return false;
}

Accountresumes.parseCurrency = function() {
    $('#SumInsured').not('[title="manual"]').blur(function(){
        $('#SumInsured').formatCurrency();
        var sum_insured = $('#SumInsured').val().replace(/,/gi, '');
        $('#AccountresumeSumInsured').val(sum_insured);
        
        // form validate
        if($('#SumInsured').val()==''){
            $('#SumInsured').parent().children('label.error-message').remove();
            $('#SumInsured').after('<label class=\"error-message\">This field is required</label>');
        } else {
            var pattern = /^[1-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{1,2})?$/.test($('#SumInsured').val());
            var pattern2 = /^[0]{1}(\.[0-9]{1,2})?$/.test($('#SumInsured').val());
            if(pattern || pattern2){
                $('#SumInsured').parent().children('label.error-message').remove();
            } else {
                $('#SumInsured').parent().children('label.error-message').remove();
                $('#SumInsured').after('<label class=\"error-message\">This field is invalid.</label>');
            }
        }
        Accountresumes.recalculator();
    });
    // manual
    $('#SumInsured[title="manual"]').blur(function(){
        $('#SumInsured').formatCurrency();
        var sum_insured = $('#SumInsured').val().replace(/,/gi, '');
        $('#AccountresumeSumInsured').val(sum_insured);
        
        // form validate
        if($('#SumInsured').val()==''){
            $('#SumInsured').parent().children('label.error-message').remove();
            $('#SumInsured').after('<label class=\"error-message\">This field is required</label>');
        } else {
            var pattern = /^[1-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{1,2})?$/.test($('#SumInsured').val());
            var pattern2 = /^[0]{1}(\.[0-9]{1,2})?$/.test($('#SumInsured').val());
            if(pattern || pattern2){
                $('#SumInsured').parent().children('label.error-message').remove();
            } else {
                $('#SumInsured').parent().children('label.error-message').remove();
                $('#SumInsured').after('<label class=\"error-message\">This field is invalid.</label>');
            }
        }
    });
    $('#GrossPremium[title="manual"]').blur(function(){
        $('#GrossPremium').formatCurrency();
        var gross_premium = $('#GrossPremium').val().replace(/,/gi, '');
        $('#AccountresumeGrossPremium').val(gross_premium);
        $('#GrossPremium').parent().find('span.selected_currency').html($('select[id="CurrencyCurrency"] :selected').text());
        
        // form validate
        if($('#GrossPremium').val()==''){
            $('#GrossPremium').parent().children('label.error-message').remove();
            $('#GrossPremium').after('<label class=\"error-message\">This field is required</label>');
        } else {
            var pattern = /^[1-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{1,2})?$/.test($('#GrossPremium').val());
            var pattern2 = /^[0]{1}(\.[0-9]{1,2})?$/.test($('#GrossPremium').val());
            if(pattern || pattern2){
                $('#GrossPremium').parent().children('label.error-message').remove();
            } else {
                $('#GrossPremium').parent().children('label.error-message').remove();
                $('#GrossPremium').after('<label class=\"error-message\">This field is invalid.</label>');
            }
        }
    });
    $('#NettPremium[title="manual"]').blur(function(){
        $('#NettPremium').formatCurrency();
        var nett_premium = $('#NettPremium').val().replace(/,/gi, '');
        $('#AccountresumeNettPremium').val(nett_premium);
        $('#NettPremium').parent().find('span.selected_currency').html($('select[id="CurrencyCurrency"] :selected').text());
        
        // form validate
        if($('#NettPremium').val()==''){
            $('#NettPremium').parent().children('label.error-message').remove();
            $('#NettPremium').after('<label class=\"error-message\">This field is required</label>');
        } else {
            var pattern = /^[1-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{1,2})?$/.test($('#NettPremium').val());
            var pattern2 = /^[0]{1}(\.[0-9]{1,2})?$/.test($('#NettPremium').val());
            if(pattern || pattern2){
                $('#NettPremium').parent().children('label.error-message').remove();
            } else {
                $('#NettPremium').parent().children('label.error-message').remove();
                $('#NettPremium').after('<label class=\"error-message\">This field is invalid.</label>');
            }
        }
    });
    $('#OrderPremium').blur(function(){
        $('#OrderPremium').formatCurrency();
        var order_premium = $('#OrderPremium').val().replace(/,/gi, '');
        $('#AccountresumeOrderPremium').val(order_premium);
        $('#OrderPremium').parent().find('span.selected_currency').html($('select[id="CurrencyCurrency"] :selected').text());
        
        // form validate
        if($('#OrderPremium').val()==''){
            $('#OrderPremium').parent().children('label.error-message').remove();
            $('#OrderPremium').after('<label class=\"error-message\">This field is required</label>');
        } else {
            var pattern = /^[1-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{1,2})?$/.test($('#OrderPremium').val());
            var pattern2 = /^[0]{1}(\.[0-9]{1,2})?$/.test($('#OrderPremium').val());
            if(pattern || pattern2){
                $('#OrderPremium').parent().children('label.error-message').remove();
            } else {
                $('#OrderPremium').parent().children('label.error-message').remove();
                $('#OrderPremium').after('<label class=\"error-message\">This field is invalid.</label>');
            }
        }
    });
}

Accountresumes.UnderWriterRates = function() {
    $('input[name="UnderWriterRates[]"]').blur(function() {
        if($(this).val()==''){
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label class=\"error-message\">This field is required</label>');
        } else {
            var pattern = /^[1-9][0-9]{0,1}(\.[0-9]+)?$/.test($(this).val());
            var pattern2 = /^[0]{1}\.[1-9]{1}([0-9]*)?$/.test($(this).val());
            if(pattern || pattern2){
                $(this).parent().children('label.error-message').remove();
            } else {
                $(this).parent().children('label.error-message').remove();
                $(this).after('<label class=\"error-message\">This field is invalid</label>');
            }
        }
    });
}

Accountresumes.MarketRates = function() {
    $('input[name="MarketRates[]"]').change(function(){
        if($(this).val()==''){
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label class=\"error-message\">This field is required</label>');
        } else {
            $(this).parent().children('label.error-message').remove();
        }
    });
}

Accountresumes.required = function() {
    $('input[title="required_date"]').change(function(){
        if($(this).val()==''){
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label style=\"display:block\" class=\"error-message\">This field is required</label>');
        } else {
            $(this).parent().children('label.error-message').remove();
        }
    });
    $('input[title="required_amount"]').blur(function(){
        if($(this).val()==''){
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label style=\"display:block\" class=\"error-message\">This field is required</label>');
        } else if($(this).val()*1 < 0) {
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label class=\"error-message\">This value can\'t be less than 0</label>');
        } else {
            $(this).parent().children('label.error-message').remove();
            Accountresumes.recalculator();
        }
    });
    // placement detail
    $('input[title="required_contact_rate"]').blur(function(){
        if($(this).val()==''){
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label class=\"error-message\">This field is required</label>');
        } else if($(this).val()*1 < 0) {
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label class=\"error-message\">This value can\'t be less than 0</label>');
        } else {
            $(this).parent().children('label.error-message').remove();
            Accountresumes.recalculator();
        }
    });
    $('input[title="required_placementdetail"]').blur(function(){
        var id = $(this).attr('id').replace('Placementdetailt', '').replace('AihRate', '').replace('ContactRate2', '').replace('BrokerageRate', '');
        if($(this).val()==''){
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label class=\"error-message\">This field is required</label>');
        } else if($(this).val()*1 < 0) {
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label class=\"error-message\">This value can\'t be less than 0</label>');
        } else if($(this).val()*1==0) {
            $(this).parent().children('label.error-message').remove();
            Accountresumes.AihSplit2(id);
        } else {
            var pattern = /^[1-9][0-9]{0,1}(\.[0-9]+)?$/.test($(this).val());
            var pattern2 = /^[0]{1}\.[1-9]{1}([0-9]*)?$/.test($(this).val());
            if(pattern || pattern2){
                $(this).parent().children('label.error-message').remove();
                Accountresumes.AihSplit2(id);
            } else {
                $(this).parent().children('label.error-message').remove();
                $(this).after('<label class=\"error-message\">This field is invalid</label>');
            }
        }
    });
    // AIH
    $('input[title="required_placementdetail2"]').blur(function(){
        var id = $(this).attr('id').replace('Placementdetailt', '').replace('AihRate', '').replace('ContactRate2', '').replace('BrokerageRate', '');
        if($(this).val()==''){
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label class=\"error-message\">This field is required</label>');
        } else if($(this).val()*1 <= 0) {
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label class=\"error-message\">This value must be greater than 0</label>');
        } else {
            var pattern = /^[1-9][0-9]{0,1}(\.[0-9]+)?$/.test($(this).val());
            var pattern2 = /^[0]{1}\.[1-9]{1}([0-9]*)?$/.test($(this).val());
            if(pattern || pattern2){
                $(this).parent().children('label.error-message').remove();
                Accountresumes.AihSplit2(id);
            } else {
                $(this).parent().children('label.error-message').remove();
                $(this).after('<label class=\"error-message\">This field is invalid</label>');
            }
        }
    });
    
    // manual
    $('input[title="required_amount_manual"]').blur(function(){
        if($(this).val()==''){
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label style=\"display:block\" class=\"error-message\">This field is required</label>');
        } else if($(this).val()*1 < 0) {
            $(this).parent().children('label.error-message').remove();
            $(this).after('<label class=\"error-message\">This value can\'t be less than 0</label>');
        } else {
            $(this).parent().children('label.error-message').remove();
        }
    });
}

Accountresumes.recurrency = function() {
    var sb = $('select#CurrencyCurrency option:selected');
    $('span.selected_currency').html(sb.text());
    $('input#AccountresumeCurrency').val(sb.text());
}

Accountresumes.recalculator = function() {
    var sb;
    var sum_insured = $('#AccountresumeSumInsured').val()*1;
    var rate = $('#AccountresumeRate').val()*1;
    // calc gross premium
    var gross_premium = sum_insured * rate /100;
    var total_days = $('#AccountresumeTotalDays').val()*1;
    if(total_days<365) {
        gross_premium = sum_insured * rate /100 * total_days /365;
    }
    if(gross_premium > 0) {
        gross_premium = Accountresumes.roundNumber(gross_premium, 2);
        $('#AccountresumeGrossPremium').val(gross_premium);
        $('#AccountresumeGrossPremium').formatCurrency('#Gross_Premium');
        sb = $('select#CurrencyCurrency option:selected');
        $('#AccountresumeGrossPremium').parent().parent().children('span.selected_currency').html(sb.text());
    }
    
    var order_hereon = $('#AccountresumeOrderHereon').val()*1; 
    // calc nett premium
    var nett_premium = gross_premium * order_hereon /100;
    if(nett_premium > 0) {
        nett_premium = Accountresumes.roundNumber(nett_premium, 2);
        $('#AccountresumeNettPremium').val(nett_premium);
        $('#AccountresumeNettPremium').formatCurrency('#Nett_Premium');
        sb = $('select#CurrencyCurrency option:selected');
        $('#AccountresumeNettPremium').parent().parent().children('span.selected_currency').html(sb.text());
    }
    
    var client_discount = $('#AccountresumeClientDiscount').val()*1; 
    // calc nett premium
    var order_premium = nett_premium * (100 - client_discount) /100;
    if(order_premium > 0) {
        order_premium = Accountresumes.roundNumber(order_premium, 2);
        $('#AccountresumeOrderPremium').val(order_premium);
        $('#AccountresumeOrderPremium').formatCurrency('#Order_Premium');
        sb = $('select#CurrencyCurrency option:selected');
        $('#AccountresumeOrderPremium').parent().parent().children('span.selected_currency').html(sb.text());
    }
    
    // calc from order_premium
    $('input[title="required_amount"]').each(function(){
        var id = $(this).attr('id').replace('broker_amount', '');
        $('#broker_amount'+id).formatCurrency();
        var broker_amount = $('#broker_amount'+id).val().replace(/,/gi, '')*1; 
        if(broker_amount > 0) {
            broker_amount = Accountresumes.roundNumber(broker_amount, 2);
            var contact_rate, aih_rate, market_amount; 
            var aih_amounts = 0;
            $('input[name="Markets[]"]').each(function(){
                var market_id = $(this).val();
                contact_rate = $('#rel_market'+market_id+' input[name*="contact_rate"]').val()*1; 
                aih_rate = $('#rel_market'+market_id+' input[name*="aih_rate"]').val()*1; 
                market_amount = broker_amount * contact_rate /100 * (100 - aih_rate) /100;
                market_amount = Accountresumes.roundNumber(market_amount, 2);
                aih_amounts += market_amount;
                $('#Paymentschedule'+id+'RelMarketAmount'+market_id).val(market_amount);
                $('#Paymentschedule'+id+'RelMarketAmount'+market_id).formatCurrency('#market_amount'+id+market_id);
            });
            $('#Paymentschedule'+id+'AihAmount').val(Accountresumes.roundNumber(broker_amount - aih_amounts, 2));
            $('#Paymentschedule'+id+'AihAmount').formatCurrency('#aih_amount'+id);
        }
    });
}

Accountresumes.sortDD = function(id) {
    if(id=='all') {
        id = 'select';
    } else {
        id = '#'+id;
    }
    // Loop for each select element on the page.
    $(id).each(function() {

        // Keep track of the selected option.
        var selectedValue = $(this).val();

        // Sort all the options by text. I could easily sort these by val.
        $(this).html($("option", $(this)).sort(function(a, b) {
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
        }));

        // Select one option.
        $(this).val(selectedValue);
    });
}

/**
 * document ready
 *
 * @return void
 */
$(document).ready(function() {
    if (Croogo.params.controller == 'accountresumes') {
        Accountresumes.documentReady();
    }
});
